package cn.sanxintong.utils.generate;

import java.io.File;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import cn.sanxintong.entity.ColumnClass;
import cn.sanxintong.entity.constant.Constant;
import cn.sanxintong.entity.constant.FileConstant;
import cn.sanxintong.entity.constant.TableConstant;
import cn.sanxintong.utils.common.JdbcTypeConvert;
import cn.sanxintong.utils.common.StrUtils;
import cn.sanxintong.utils.freemarker.FreeMarkerTemplateUtils;

/**
 * 生成实体类的工具类
 * @author hxy
 * @version 1.0.0
 */
public class ModelUtil {

	public static void generateModelFile(ResultSet resultSet) throws Exception{
        final String path = Constant.DISK_PATH + StringUtils.substring(Constant.CHANGE_TABLE_NAME,3) + FileConstant.JAVA_SUFFIX;
        final String templateName = "Model.ftl";
        File mapperFile = new File(path);
        List<ColumnClass> columnClassList = new ArrayList<>();
        ColumnClass columnClass = null;
        while(resultSet.next()){
            //id字段略过
            if(resultSet.getString(TableConstant.COLUMN_NAME).equals("id")) continue;
            columnClass = new ColumnClass();
            //获取字段名称
            columnClass.setColumnName(resultSet.getString(TableConstant.COLUMN_NAME));
            //转换字段名称，如 sys_name 变成 SysName
            columnClass.setChangeColumnName(StrUtils.replaceUnderLineAndUpperCase(resultSet.getString(TableConstant.COLUMN_NAME)));
            //字段在数据库的注释
            columnClass.setColumnComment(resultSet.getString(TableConstant.REMARKS));
            //获取字段类型
            //System.out.println(JdbcTypeConvert.mysqlType2JavaType(resultSet.getString(TableConstant.TYPE_NAME)));
            columnClass.setColumnType(JdbcTypeConvert.mysqlType2JavaType(resultSet.getString(TableConstant.TYPE_NAME)));
            columnClassList.add(columnClass);
        }
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("model_column",columnClassList);
        FreeMarkerTemplateUtils.generateFileByTemplate(templateName,mapperFile,dataMap);
        System.out.println("生成实体类");
	}
	
}
